package client

import (
	"github.com/akirakazu/go-simplejson"
	"time"
)

type waiter struct {
	msg           *json.Json
	fn            func(string, *json.Json, *json.Json)
	t             time.Duration
	timeout       *chan bool
	cancelTimeout *chan bool
}

func newWaiter(msg *json.Json, t time.Duration, fn func(string, *json.Json, *json.Json)) {
	w := new(waiter)
	w.msg = msg
	w.t = t
	w.fn = fn
	w.timeout = make(chan bool)
	w.cancelTimeout = make(chan bool)
	return w
}

func (w *waiter) start(string id) {
	go func() {
		time.Sleep(w.t)
		w.timeout <- true
	}()
	select {
	case <-w.timeout:
		res := json.New()
		res.Set("err", "timeout")
		w.fn(id, w.msg, res)
		w.dispose()
	case <-w.cancelTimeout:
		return
	}
}

func (w *waiter) dispose() {
	w.msg = nil
	w.fn = nil
	w.t = nil
	w.timeout = nil
	w.cancelTimeout = nil
}
